package com.lms.realm;

import com.lms.bean.Permission;
import com.lms.bean.Role;
import com.lms.bean.User;
import com.lms.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class LmsRealm extends AuthorizingRealm {

    public void SetName(String name){
        setName("LmsRealm");
    }

    @Autowired
    private UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user=(User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Role role =user.getRole();
        info.addRole(role.getRolename());
        for(Permission permission:role.getPermissions()){
            info.addStringPermission(permission.getCode());
        }
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //从session里面把user
        //shito token
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
        String username=usernamePasswordToken.getUsername();
        String password=new String(usernamePasswordToken.getPassword());
        User user=userService.checkUser(username,password);
        if(user!=null){
            return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        }
        return null;
    }

    public void clearCachedAuthorization(){
        //清空权限缓存
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
